<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">

		<meta name="renderer" content="webkit">
		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
		<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
		<meta name="format-detection" content="telephone=no">
		<link rel="stylesheet" href="../../layui/css/layuilast.css" media="all">
		<link rel="stylesheet" href="https://cdn.bootcss.com/font-awesome/4.7.0/css/font-awesome.css">

	</head>

	<body>
		<div id="tabDIV" style="display: block">
			<div class="layui-row" style="margin-top: 3vh;">
				<div class="layui-inline">
					<label class="layui-form-label" type="button" value="查询">用户名</label>
					<div class="layui-input-inline">
						<input type="text" id="bindUserLoginNo1" autocomplete="off" class="layui-input"
							placeholder="用户账号">
					</div>
				</div>

				<!--<div class="layui-inline">
                <label class="layui-form-label">名称</label>
                <div class="layui-input-inline">
                    <input type="tel" id="bindRealName1" autocomplete="off" class="layui-input" placeholder="用户名称">
                </div>
            </div>-->

				<div class="layui-inline">
					<label class="layui-form-label" type="button" value="查询">手机号</label>
					<div class="layui-input-inline">
						<input type="tel" id="bindUserPhone1" autocomplete="off" class="layui-input"
							placeholder="用户手机号">
					</div>
				</div>

				<div class="layui-inline" style="float: right;margin-top: 1vh;margin-right: 1vh">
					<button class="layui-btn" onclick="reset()">
						<i class="layui-icon layui-icon-delete"></i>清除
					</button>
					<button class="layui-btn" onclick="search1()">
						<i class="layui-icon layui-icon-search"></i>查询
					</button>

				</div>
			</div>
			<table id="table" lay-filter="table"></table>
		</div>


		<div id="editForm" style="display: none;>
        <form id=" updateForm" enctype="multipart/form-data">
			<div class="layui-card-body layui-form">
				<!-- <input type="hidden" name="username" id="id"> -->
				<div class="layui-form-item">
					<div class="layui-inline">
						<label class="layui-form-label">用户名</label>
						<div class="layui-input-block">
							<input id="bindUserLoginNo" type="text" disabled="disabled" name="username"
								autocomplete="off" class="layui-input" placeholder="填写登录账号" required="required">
						</div>
					</div>
				</div>

				<div class="layui-form-item">
					<div class="layui-inline">
						<label class="layui-form-label">登录密码</label>
						<div class="layui-input-block">
							<input type="password" name="password" id="password" autocomplete="off" class="layui-input"
								placeholder="密码" required="required">
							<input type="checkbox" name="display" lay-filter="switchDisplay" title="显示密码"
								value="display">
						</div>
					</div>
				</div>


				<div class="layui-form-item">
					<div class="layui-inline">
						<label class="layui-form-label">手机号</label>
						<div class="layui-input-block">
							<input type="text" name="phone" autocomplete="off" class="layui-input" placeholder="填写手机号"
								required="required">
						</div>
					</div>
				</div>




				<div class="layui-form-item">
					<div class="layui-inline">
						<label class="layui-form-label">公司名称</label>
						<div class="layui-input-block">
							<input type="text" name="realname" autocomplete="off" class="layui-input" placeholder="公司名称"
								required="required">
						</div>
					</div>
				</div>





				<div class="layui-form-item">
					<div class="layui-inline">
						<label class="layui-form-label">公司负责人</label>
						<div class="layui-input-block">
							<input type="text" id="binddesc" name="binddesc" autocomplete="off" class="layui-input"
								placeholder="公司负责人" required="required">
						</div>
					</div>
				</div>


			</div>
		</div>
		</form>
		</div>



	</body>


	<script charset="utf-8" src="../../layui/js/jquery/jquery.js"></script>
	<script charset="utf-8" src="../../layui/js/jquery/jquery.serializeJSON.js"></script>
	<script charset="utf-8" src="../../layui/layuilast.js"></script>
	<script charset="utf-8" src="../../layui/js/md5/md5.min.js"></script>
	<script charset="utf-8" src="../../layui/js/extend/common.js"></script>
	<!--<script src="../../js/http.js"></script>-->
	<script type="text/javascript">
		var rootUrl = localStorage.getItem('rootUrl');
		var pageAPI = {
			pageURL: rootUrl + '/user/getUserList'
		}
		console.log(rootUrl);

		var url_add = "\/yk\/admin\/mita\/account\/addDeviceManger";
		var url_edit = "\/yk\/ykAdminDevManger\/updateBindUserInfo";
		var url_bind_device = "\/yk\/ykAdminDevManger\/bindAdminDevice";
		var url_unBind_device = "\/yk\/ykAdminDevManger\/unBindAdminDevice";
		var uploadURL = "\/yk\/file\/fileWebUpload";
		var tableId = "table";
		var selectUserId;
		let files = '';
		var opUserId = 1;
		var cols = [
			[{
					title: '序号',
					templet: '#indexTpl',
					width: 100
				},
				// {field: 'id',title: '用户ID', hide:false},
				{
					field: 'userName',
					title: '用户名'
				},
				{
					field: 'password',
					title: '密码'
				},
				{
					field: 'phone',
					title: '手机号'
				},
				{
					field: 'companyName',
					title: '公司名称',
					templet: function(d) {
						return d.createtime == null ? '' : d.createtime.replace("T", " ").substring(0, 19);
					}
				},
				{
					field: "companyLeader",
					title: '公司负责人'
				},
				{
					field: 'time',
					title: '绑定时间',
					templet: function(d) {
						return d.createtime == null ? '' : d.createtime.replace("T", " ").substring(0, 19);
					}
				},
				{
					toolbar: "#barDemo",
					align: 'center',
					title: '操作',
					width: 254,
					align: 'left'
				}

			]
		];



		//表格数据初始化
		if (!localStorage.getItem('token') || !localStorage.getItem('userid')) {
			window.location.href = '../login/login.html'
		} else {
			// console.log('进来了',localStorage.getItem('token'));
			initTab(tableId, "#table", "table", pageAPI.pageURL, cols, { //这些都是layui里面的
				upuserid: localStorage.getItem('userid'),
				userid: localStorage.getItem('userid'),
				token: localStorage.getItem('token')
			}, null, null)
		}

		function reset() {

			window.location.reload();
		}



		//条件查询
		function search1() {
			console.log("测试查询")
			//       var table = layui.table;

			var url = rootUrl + "/user/getUserListByNameAndPhone";
			var username = $("#bindUserLoginNo1").val();
			var realname = $("#bindRealName1").val();
			var phone = $("#bindUserPhone1").val();
			console.log(username + " : " + localStorage.getItem('userid'));
			initTab(tableId, "#table", "table", url, cols, {
				username: username,
				realname: realname,
				phone: phone,
				userid: localStorage.getItem('userid'),
				token: localStorage.getItem('token')
			}, null, null)

		} //end search1

		//新增
		$("#btn-add").click(function() {
			$("#updateForm")[0].reset();
			$(".headImg").prop("src", "");
			// $("#id").val("");
			$("#bindUserLoginNo").attr("disabled", false);
			openEditForm('add');
		});
		//打开编辑框
		function openDevEditForm() {
			layer.open({
				type: 1,
				skin: 'layui-layer-demo', //样式类名
				// skin: 'layui-layer-rim', //加上边框
				area: ['90%', '90%'], //宽高
				anim: 2,
				shadeClose: true, //开启遮罩关闭,
				maxmin: true,
				title: "设备分配列表",
				content: $("#deviceListForm"),
				btn: ['关闭'],
				no: function(index, layero) {


				}
			});
		}

		function visitimg(src) {

			var img = new Image();
			img.src = src;
			var imgHtml = "<img src='" + src + "' width='500px' height='500px'/>";
			console.log("visitimg");
			//弹出层
			layer.open({
				type: 1,
				shade: 0.8,
				offset: 'auto',
				area: [500 + 'px', 550 + 'px'],
				shadeClose: true,
				scrollbar: false,
				title: "图片预览", //不显示标题  
				content: imgHtml, //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响  
				cancel: function() {
					//layer.msg('捕获就是从页面已经存在的元素上，包裹layer的结构', { time: 5000, icon: 6 });  
				}
			});
		}

		//打开编辑框
		function openEditForm(type, obuserid) {
			console.log(openEditForm)
			$('#prompt').text('')
			layer.open({
				type: 1,
				skin: 'layui-layer-demo', //样式类名
				area: ['80%', '80%'], //宽高
				anim: 2,
				shadeClose: true, //开启遮罩关闭,
				maxmin: true,
				title: "个人信息",
				content: $("#editForm"),
				/*btn: ['提交','关闭'],*/
				yes: function(index, layero) {
					console.log("看是否进入")
					const data = $('#updateForm').getData();
					const formData = new FormData($("#updateForm")[0]);
					for (var key in data) {
						var element = data[key];
						if (key != "password" && key != 'upload') {
							console.log("key->" + key + "  element = " + element)
							if (element == null || element == '' || element == undefined) {
								layer.alert("表单数据没有填写完全!");
								return;
							}
						}
					}

					formData.append('upload', files)
					formData.append('token', localStorage.getItem('token')),
						formData.append('userid', localStorage.getItem('userid'))
					switch (type) {
						case 'add':
							let val = $("input[name=password]").val();
							console.log('查看添加的值', val);
							if (val == '' || files == '') {
								layer.alert("表单数据没有填写完全!");
								return;
							}
							$.ajax({
								url: rootUrl + "/user/addSubAdministator",
								asynnc: false,
								cache: false,
								data: formData,
								dataType: 'json',
								contentType: false,
								processData: false,
								type: 'post',
								success: function(res) {
									if (res.errorcode == 0) {
										layer.msg(res.resultmsg);
										location.reload();
									} else {
										layer.msg(res.resultmsg);
									}

								},
								error: function(res) {
									// 服务器繁忙
									alert('服务器繁忙');
								},

							});

							break;
						case 'edit':
							//console.log("obuserid:"+obuserid);

							formData.append('obuserid', obuserid)
							if (files === '') {
								// layer.msg('请重新上传头像');
								$.ajax({
									url: rootUrl + "/user/modifySubAdministatorNoPic",
									asynnc: false,
									cache: false,
									data: formData,
									dataType: 'json',
									contentType: false,
									processData: false,
									type: 'post',
									success: function(res) {
										if (res.errorcode == 0) {
											layer.msg(res.resultmsg);
											location.reload();
										} else {
											layer.msg(res.resultmsg);
										}
									},
									error: function(res) {
										// 服务器繁忙
										alert('服务器繁忙');
									},
								});
								return true;
							}
							$.ajax({
								url: rootUrl + "/user/modifySubAdministator",
								asynnc: false,
								cache: false,
								data: formData,
								dataType: 'json',
								contentType: false,
								processData: false,
								type: 'post',
								success: function(res) {
									if (res.errorcode == 0) {
										layer.msg(res.resultmsg);
										location.reload();
									} else {
										layer.msg(res.resultmsg);
									}

								},
								error: function(res) {
									// 服务器繁忙
									alert('服务器繁忙');
								},

							});
					}
				}
			});
		}
		layui.use(['table', 'form', 'upload'], function() {
			var table = layui.table;
			var form = layui.form();
			var upload = layui.upload;
			//监听多选框点击事件  主要是通过 lay-filter="switchTest"  来监听
			form.on('checkbox(switchDisplay)', function(data) {
				console.log(data); //打印当前选择的信息
				var showPwd = $("#password");
				if (data.elem.checked) { //判断当前多选框是选中还是取消选中
					showPwd.prop('type', 'text');
				} else {
					showPwd.prop('type', 'password');
				}
				var value = data.value; //获取选中的value值
			});


			//上传图片
			upload.render({
				elem: '#upload_img',
				url: uploadURL,
				choose: function(res) {
					//上传完毕回调
					//预读本地文件，如果是多文件，则会遍历。(不支持ie8/9)
					res.preview(function(index, file, result) {
						console.log(index); //得到文件索引
						console.log('文件对象', file); //得到文件对象
						// console.log(result); //得到文件base64编码，比如图片
						$("#prompt").text(file.name);
						$("#headImg").val(file);
						files = file
						$(".headImg").prop("src", result);
					});
				},
			}); //end render


			//删除和修改
			table.on('tool(table)', function(obj) {
				var data = obj.data;
				if (obj.event === 'del') { //删除
					layer.confirm('真的删除行么', function(index) {
						$.post(delURL, {
							id: data.id
						}, function(resp) {
							if (resp.success) {
								window.location.reload();
							}
							console.info(resp.info);
						})
						layer.close(index);
						$("#query-btn").click();
					});
				} else if (obj.event === 'edit') {
					// console.log(data);
					$('#updateForm').loadData(data);
					//$(".headImg").prop("src", data.avatarurl);
					// files=data.avatarurl
					$("#id").val(data.id);
					$("input[name=password]").val(data.password);
					$("#phone").val(data.phone);
					$("#binddesc").val(data.bindDesc);
					$("#bindUserLoginNo").attr("disabled", true);
					/*$(".headImg").prop("src", rootURL+data.avatarurl);*/

					form.render();
					openEditForm('edit', data.userId);
				} else if (obj.event === 'delete') {
					var tableId = "devListTable";
					var obuserid = obj.data.userId;
					$.ajax({
						url: rootUrl + "/user/deleteUser",
						asynnc: false,
						cache: false,
						data: {
							obuserid: obuserid,

							userid: localStorage.getItem('userid'),
							token: localStorage.getItem('token')
						},
						dataType: 'json',

						type: 'post',
						success: function(res) {
							if (res.errorcode == 0) {
								layer.msg(res.resultmsg);
								location.reload();
							} else {
								layer.msg(res.resultmsg);
							}

						},
						error: function(res) {
							// 服务器繁忙
							alert('服务器繁忙');
						},

					}); //end ajax
				} else if (obj.event === 'deviceManger') {
					var tableId = "devListTable";
					opUserId = obj.data.userId;
					console.log(opUserId);
					var cols = [
						[{
								title: '序号',
								templet: '#indexTpl',
								width: 50
							},
							// {field: 'id',title: '用户ID', hide:false},
							// {field: 'phone', title: '手机号'},
							// {field: 'userName', title: '用户名'},
							{
								field: 'deviceSn',
								title: '设备编号'
							},
							{
								field: 'addTime',
								title: '绑定管理时间',
								templet: function(d) {
									if (d.updatetime != null && d.updatetime != undefined) {
										return d.updatetime.replace("T", " ").substring(0, 19);
									} else {
										return "未绑定管理";
									}

								}
							},
							{
								field: 'deviceDesc',
								title: '设备描述'
							},
							{
								field: 'adminName',
								title: '设备管理人'
							},
							{
								field: "adminPhone",
								title: '管理人手机'
							},
							{
								field: "address",
								title: '设备地址'
							},
							{
								field: "city",
								title: '设备所在城市'
							},
							{
								toolbar: "#operation",
								align: 'center',
								title: '操作',
								width: 154,
								align: 'left'
							}
						]
					];
					console.log(pageDeviceURL);

					//表格数据初始化
					initTab(tableId, "#devListTable", "devListTable", pageDeviceURL, cols, {
						adminuserid: opUserId,
						userid: localStorage.getItem('userid'),
						token: localStorage.getItem('token')
					}, null);
					openDevEditForm();
				} //end else

			}); //end on


			table.on('tool(devListTable)', function(obj) {
				var data = obj.data;
				console.log(data);
				if (obj.event === 'dist') {

					// data.userId=selectUserId;
					var bindData = {};
					bindData.userId = selectUserId;
					bindData.deviceMac = data.deviceMac;
					console.log(opUserId);
					console.log("--------->" + JSON.stringify(data))
					$.ajax({
						url: rootUrl + "/device/modifyDeviceAdmin",
						asynnc: false,
						cache: false,
						data: {
							deviceid: data.deviceId,
							adminuserid: opUserId,

							userid: localStorage.getItem('userid'),
							token: localStorage.getItem('token')
						},
						dataType: 'json',

						type: 'post',
						success: function(res) {
							if (res.errorcode == 0) {
								layer.msg(res.resultmsg);
								//location.reload();
								table.reload('devListTable');
							} else {
								layer.msg(res.resultmsg);
							}

						},
						error: function(res) {
							// 服务器繁忙
							alert('服务器繁忙');
						},

					});

				} else if (obj.event === 'undist') {
					$.ajax({
						url: rootUrl + "/device/modifyDeviceAdmin",
						asynnc: false,
						cache: false,
						data: {
							deviceid: data.deviceId,
							adminuserid: localStorage.getItem('userid'),

							userid: localStorage.getItem('userid'),
							token: localStorage.getItem('token')
						},
						dataType: 'json',

						type: 'post',
						success: function(res) {
							if (res.errorcode == 0) {
								layer.msg(res.resultmsg);
								table.reload('devListTable');
							} else {
								layer.msg(res.resultmsg);
							}

						},
						error: function(res) {
							// 服务器繁忙
							alert('服务器繁忙');
						},

					});


				} //end else



			}) //end table.on

			// //启用禁用开关
			form.on('switch(isEnable)', function(obj) {
				var isDelete;
				var tips;
				var title;
				//console.log(obj.value)
				if (obj.value == 1) {
					layer.msg('超级管理员不能禁用!');
					return;
				}
				if (obj.elem.checked) {

					title = "确定禁用";
					tips = "确定禁用用户吗";
					isDelete = 1;
				} else {
					isDelete = 0;
					title = "确定启用";
					tips = "确定启用用户吗";
				}
				layer.confirm(tips, {
					title: title
				}, function(index) {
					var id = obj.value;
					layer.close(index);

					$.ajax({
						url: rootUrl + "/user/setUserPermit",
						asynnc: false,
						cache: false,
						data: {
							obuserid: id,
							permitstate: isDelete,
							userid: localStorage.getItem('userid'),
							token: localStorage.getItem('token')
						},
						dataType: 'json',

						type: 'post',
						success: function(res) {
							if (res.errorcode == 0) {
								layer.msg(res.resultmsg);
								//location.reload();
							} else {
								layer.msg(res.resultmsg);
							}

						},
						error: function(res) {
							// 服务器繁忙
							alert('服务器繁忙');
						},

					});


				}); //end confirm
			}); //end on

		}); //end use
	</script>


	<!--table的序号-->
	<script type="text/html" id="indexTpl">
	{{d.LAY_TABLE_INDEX+1}}
	</script>

	<!-- 启用禁用开关-->
	<script type="text/html" id="isEnableStatus">
	{{# if(d.permitstate == 1){ }}
		<input type="checkbox" value="{{d.userId}}" lay-skin="switch" lay-text="是|否" lay-filter="isEnable"
			checked="checked" />
		{{# }else if(d.permitstate==0){ }}
			<input type="checkbox" value="{{d.userId}}" lay-skin="switch" lay-text="是|否" lay-filter="isEnable" />
			{{# } }}
	</script>

	<!--table的操作按钮-->
	<script type="text/html" id="barDemo">
		<a class="layui-btn layui-btn-xs" lay-event="edit" onclick="editForm">详情</a>
	</script>
	<!--table的操作按钮-->
	<script type="text/html" id="operation">
	{{# if(d.adminUserId != opUserId){ }}
		<a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="dist">分配</a>
		{{# }else if(d.adminUserId==opUserId){ }}
			<a class="layui-btn layui-btn-xs " lay-event="undist">取消</a>
			{{# } }}
	</script>

</html>
